import frappe
from frappe import _
from frappe.utils import now
from .sales_order_status_manager import SalesOrderStatusManager

@frappe.whitelist()
def get_custom_status_options():
    """获取自定义状态选项"""
    return SalesOrderStatusManager.get_custom_status_options()

@frappe.whitelist()
def get_all_status_options():
    """获取所有状态选项"""
    return SalesOrderStatusManager.get_all_status_options()

@frappe.whitelist()
def get_status_form_fields(status):
    """获取状态对应的表单字段"""
    if not SalesOrderStatusManager.is_custom_status(status):
        return []
    return SalesOrderStatusManager.get_status_form_fields(status)

@frappe.whitelist()
def get_editable_fields(status):
    """获取指定状态下的可编辑字段"""
    return SalesOrderStatusManager.get_editable_fields(status)

@frappe.whitelist()
def check_field_edit_permission(sales_order, field_name):
    """检查字段编辑权限"""
    try:
        doc = frappe.get_doc("Sales Order", sales_order)
        current_status = doc.status
        
        # 如果是自定义状态，检查字段是否在可编辑列表中
        if SalesOrderStatusManager.is_custom_status(current_status):
            editable_fields = SalesOrderStatusManager.get_editable_fields(current_status)
            return field_name in editable_fields
        
        # 非自定义状态，使用默认权限
        return True
    except Exception as e:
        frappe.log_error(f"检查字段编辑权限失败: {str(e)}")
        return False

@frappe.whitelist()
def update_sales_order_status(sales_order, new_status, form_data=None):
    """更新销售订单状态"""
    try:
        # 检查权限
        if not frappe.has_permission("Sales Order", "write"):
            frappe.throw(_("您没有权限修改销售订单状态"))
        
        # 获取销售订单
        so = frappe.get_doc("Sales Order", sales_order)
        
        # 检查是否为自定义状态
        if SalesOrderStatusManager.is_custom_status(new_status):
            # 验证表单数据
            if not form_data:
                frappe.throw(_("切换到自定义状态需要填写相关信息"))
            
            # 解析表单数据
            if isinstance(form_data, str):
                import json
                form_data = json.loads(form_data)
            
            # 验证必填字段
            required_fields = SalesOrderStatusManager.get_status_form_fields(new_status)
            for field in required_fields:
                if field.get("reqd") and not form_data.get(field["fieldname"]):
                    frappe.throw(_("字段 {0} 是必填的").format(field["label"]))
            
            # 保存自定义字段数据
            for field in required_fields:
                fieldname = field["fieldname"]
                if fieldname in form_data:
                    so.set(fieldname, form_data[fieldname])
        
        # 更新状态
        so.status = new_status
        so.save()
        
        # 记录状态变更日志
        frappe.get_doc({
            "doctype": "Comment",
            "comment_type": "Info",
            "reference_doctype": "Sales Order",
            "reference_name": sales_order,
            "content": _("状态变更为: {0}").format(new_status)
        }).insert(ignore_permissions=True)
        
        frappe.db.commit()
        
        return {
            "status": "success",
            "message": _("状态更新成功"),
            "new_status": new_status
        }
        
    except Exception as e:
        frappe.log_error(f"更新销售订单状态失败: {str(e)}")
        return {
            "status": "error",
            "message": str(e)
        }

@frappe.whitelist()
def get_status_history(sales_order):
    """获取状态变更历史"""
    comments = frappe.get_all(
        "Comment",
        filters={
            "reference_doctype": "Sales Order",
            "reference_name": sales_order,
            "comment_type": "Info"
        },
        fields=["content", "creation", "owner"],
        order_by="creation desc"
    )
    return comments
